// packageB/pages/package/liangdeng/bind_positon/bind_positon.js
const mybehavior = require("../../../../../behaviors/requests")
import WxValidate from "../../../../../Wx_Validate/WxValidate"
import Dialog from '@vant/weapp/dialog/dialog';

Page({

  /**
   * 页面的初始数据
   */
  behaviors: [mybehavior],
  data: {
    baseUrl: "https://logisticsengineering.gree.com/smartg_api/storage_racks_manage",
    pickup_code: "",
    _ids: [],
    take_out: false,
    take_out0: false,
    location: [],
    data_list: "",
    people: [],
    num: [],
    location_arr: [],
    cabinet_id: "cabinet_id_001",
    label_style: "width: 200rpx;",
    style3: "width: 430rpx;",
    checkbox_value: [],
    btn_disabled: true,
    btn_str: '确认',
    count: 5,
  },
  onCheckboxChange(e) {
    console.log(e);
    this.setData({
      checkbox_value: e.detail
    })
  },
  // 查询--网点名称--集合
  getCabinetData() {
    let url = "https://logisticsengineering.gree.com/smartg_api/cabinet_manage/query_cabinet";
    let data = {
      page: 1,
      pagesize: 9999,
    }

    this.post(url, data).then(res => {
      console.log("返回结果", res)
      if (res.code == 20000) {

        this.setData({
          options1: res.data.results,
        })

      } else {
        wx.showToast({
          title: res.msg,
          icon: "error"
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  // 下拉选择
  getPickerVlaue(e) {
    console.log(e);
    let key = e.target.id
    this.setData({
      [key]: e.detail._id,
      cabinet_id_name: e.detail.name,
    })

  },
  // 扫描
  scan1(e) {
    console.log(e.currentTarget.dataset.row_data);
    let key = e.currentTarget.dataset.row_data
    const self = this;
    wx.scanCode().then((res) => {
      const label_code = res.result;
      wx.showLoading({
        title: "loading"
      })
      console.log(label_code);
      setTimeout(function () {
        wx.hideLoading()
        self.setData({
          [key]: label_code
        })
      }, 500)
    }).catch(err => {
      console.log(err);
    });
  },



  // 查询物料
  searchInfo() {
    if (this.data.pickup_code == "") {
      wx.showToast({
        title: '取件码不能为空！',
        icon: 'error'
      })
    } else {
      let url = this.data.baseUrl + "/query_materials"
      let data = {
        cabinet_id: this.data.cabinet_id,
        pickup_code: this.data.pickup_code,
      }
      console.log(data);
      this.post(url, data).then(res => {

        if (res.code == 20000) {
          console.log(res);
          // let lists = JSON.parse(JSON.stringify(this.data._ids))
          this.setData({
            _ids: res.data,
            take_out0: true,

          })
          wx.showToast({
            title: "查询成功",
            icon: 'success'
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'error'
          })
        }
      }).catch(err => {
        console.log(err);
        wx.showToast({
          title: err.msg,
          icon: 'error'
        })
      })

    }
  },

  // 确认取件
  confirmOut() {
    let url = this.data.baseUrl + "/take_out"
    let arr = []
    const lists = this.data.checkbox_value

    let data = {
      _ids: lists,
    }
    console.log("确认取件返回数据", data);
    this.post(url, data).then(res => {

      if (res.code == 20000) {
        console.log(res.data);
        let lists = []
        for (let j in res.data) {
          lists.push(res.data[j].box_no)
        }
        console.log("库位号列表", lists);
        let arr2 = []

        const arr1 = Array.from(new Set(lists))
        console.log("去重后", arr1);
        for (let b in arr1) {
          let obj = {
            box_no: "",
            contact: [],
            business_id: [],
            location_arr: arr
          }
          for (let c in res.data) {
            if (arr1[b] == res.data[c].box_no) {
              obj.box_no = res.data[c].box_no
              obj.contact.push(res.data[c].contact)
              obj.business_id.push(res.data[c].business_id)
            }
          }
          arr2.push(obj)

        }
        console.log("组装数据", arr2);

        this.setData({
          location: arr1,
          data_list: arr2,
          take_out: true,
          take_out0: false,
          btn_disabled: true,
          show: true,
        })
        // //刷新取件模板
        this.flashLabel()
        this.timeDown()

        // wx.showModal({
        //   content: this.data.cabinet_id_name + ":" + this.data.location,
        //   showCancel: false,
        //   complete: (res) => {
        //     if (res.confirm) {
        //       this.getPositionDatas()

        //     }
        //   }
        // })

      } else {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })

  },
  // 倒计时
  timeDown() {
    let c = this.data.count
    console.log("xxx", c);
    if (c > 0) {
      this.setData({
        btn_str: '(' + c + 's)' + '确认',
        count: c - 1
      })
      setTimeout(() => {
        this.timeDown()
      }, 1000)
    } else {
      this.setData({
        btn_disabled: false,
        btn_str: '确认',
      })

    }

  },


  // 取件模板
  flashLabel() {
    let url = "https://logisticsengineering.gree.com/order_system/smart_ld"
    let lists = this.data.data_list

    console.log("亮灯数据", lists);


    for (let i in lists) {
      let data = {
        location: lists[i].box_no,
        code: this.data.pickup_code,
        ldORmd: 1,
        people: lists[i].contact,
        num: lists[i].business_id,
        date: this.formatDate(new Date()),
      }

      this.post(url, data).then(res => {

        if (res.code == 20000) {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'error'
          })
        }
      }).catch(err => {
        console.log(err);
        wx.showToast({
          title: err.msg,
          icon: 'error'
        })
      })
    }


  },

  // 获取该库位数据信息
  getPositionDatas() {
    let url = this.data.baseUrl + "/query_msg_by_location_code"
    let lists = this.data.data_list

    console.log("亮灯数据", lists);
    // 获取库位列表
    for (let i in lists) {
      // 循环库位列表获取库位信息
      let data = {
        location_code: lists[i].box_no,
        cabinet_id: "cabinet_id_001",
      }
      this.post(url, data).then(res => {
        console.log("获取该库位数据信息", res.data)
        let num_arr = []
        let people_arr = []
        for (let i in res.data) {
          num_arr.push(res.data[i].business_id)
          people_arr.push(res.data[i].contact)
        }

        if (res.code == 20000) {
          this.setData({
            num: num_arr,
            people: people_arr,
            show: false,
            btn_str: '确认',
            count: 5,
            btn_disabled: true,
            checkbox_value: []

          })
          this.lightOff(lists[i].box_no)

        } else {
          wx.showToast({
            title: res.msg,
            icon: 'error'
          })
        }
      }).catch(err => {
        console.log(err);
        wx.showToast({
          title: err.msg,
          icon: 'error'
        })
      })
    }
    this.timeOutFlash()
    this.setData({
      _ids: [],
      take_out: false,
      pickup_code: ""

    })



  },

  // 访问后台延时刷新接口
  timeOutFlash() {
    let url = this.data.baseUrl + "/cancel_refresh"
    let data = {
      location: this.data.location_arr,
    }
    this.post(url, data).then(res => {
      if (res.code == 20000) {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })

  },

  // 确认取件后刷新模板
  lightOff(e) {
    let url = "https://logisticsengineering.gree.com/order_system/smart_ld"
    let data = {
      location: e,
      ldORmd: 0,
      people: this.data.people,
      num: this.data.num,
      code: this.data.pickup_code,
      date: this.formatDate(new Date()),
    }
    this.post(url, data).then(res => {
      if (res.code == 20000) {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
        setTimeout(()=>{
          wx.navigateTo({
            url: '/packageB/pages/package/smart_box/smart_box',
          })
        },1000)
        this.setData({
          position_list: [],
          position_list1: [],
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })

  },
  clearData() {
    this.setData({
      _ids: [],
      take_out: false,


    })
    // 灭灯操作
    this.getPositionDatas()
  },
  // 当前用户物料查询
  userMaterials() {
    let url = this.data.baseUrl + "/query_user_materials "

    let data = {
      cabinet_id: "cabinet_id_001",
      email: wx.getStorageSync('email')
    }
    console.log(data);
    this.post(url, data).then(res => {

      if (res.code == 20000) {
        console.log("当前用户物料查询", res.data);

        this.setData({
          take_out0: true,
          _ids: res.data,
          pickup_code: res.data[0].pickup_code
        })
        // wx.showToast({
        //   title: res.msg,
        //   icon: 'success'
        // })
      } else {
        console.log(res.msg);
        // wx.showToast({
        //     title: res.msg,
        //     icon: 'error'
        //   })
      }
    }).catch(err => {
      console.log(err);
      // wx.showToast({
      //   title: err.msg,
      //   icon: 'error'
      // })
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let self = this
    const eventChannel = this.getOpenerEventChannel()
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('acceptDataFromOpenerPage', function (data,data2,data3) {
      console.log("传过来的数据", data,data2,data3)
      let checkBox = []
      for (let i = 0; i < data.length; i++) {
        checkBox.push(data[i]._id)
        
      }
      self.setData({
        _ids: data,
        take_out0:true,
        cabinet_id_name:data2,
        checkbox_value:checkBox,
        cabinet_id_location:data3,
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})